package com.job.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.job.client.common.result.AppHttpCode;
import com.job.client.common.result.ResponseResult;
import com.job.client.common.utils.DateTimeUtils;
import com.job.client.common.utils.JwtTokenUtils;
import com.job.client.model.auth.pojo.User;
import com.job.search.dto.CompanySearchDto;
import com.job.search.dto.PostsSearchDto;
import com.job.search.mapper.HistoryMapper;
import com.job.search.pojo.History;
import com.job.search.service.SearchCompanyService;
import com.job.search.service.SearchPostsService;
import com.job.search.service.SearchService;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class SearchServiceImpl implements SearchService {
    @Autowired
    private SearchPostsService postsService;
    @Autowired
    private SearchCompanyService companyService;
    @Autowired
    private HistoryMapper historyMapper;
    @Override
    public ResponseResult getPostsCompanyByName(String name) {
        if(name == null){
            return ResponseResult.ErrorResult(AppHttpCode.DATA_NULL);
        }
        ResponseResult postsSearch = postsService.searchHighlight(new PostsSearchDto(name, ""));
        ResponseResult companySearch = companyService.searchHighlight(new CompanySearchDto(name, ""));
        if(postsSearch.getCode() != 200){
            return postsSearch;
        }
        if(companySearch.getCode() != 200){
            return companySearch;
        }
        Map<String, Object> data = new HashMap<>();
        data.put("posts",postsSearch.getData());
        data.put("company",companySearch.getData());
        return ResponseResult.OkResult(data);
    }

    @Override
    public ResponseResult saveHistory(String content, HttpServletRequest request) {
        ResponseResult result = getUserInfo(request);
        if(result.getCode()!=200){
            return result;
        }
        User user = JSON.parseObject(JSON.toJSONString(result.getData()), User.class);
        if(user==null){
            return ResponseResult.ErrorResult(AppHttpCode.SERVICE_ERROR);
        }
        if(content==null){
            return ResponseResult.ErrorResult(AppHttpCode.DATA_NULL);
        }
        History history = new History(user.getUserId(),content, DateTimeUtils.createNowTime());
        int i = historyMapper.insert(history);
        if(i!=1){
            return ResponseResult.ErrorResult(AppHttpCode.SERVICE_ERROR);
        }
        return ResponseResult.OkResult();
    }

    @Override
    public ResponseResult getHistory(HttpServletRequest request) {
        ResponseResult result = getUserInfo(request);
        if(result.getCode()!=200){
            return result;
        }
        User user = JSON.parseObject(JSON.toJSONString(result.getData()), User.class);
        if(user==null){
            return ResponseResult.ErrorResult(AppHttpCode.SERVICE_ERROR);
        }
        QueryWrapper<History> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",user.getUserId());
        List<History> historyList = historyMapper.selectList(queryWrapper);
        // 数据去重并且返回time最大的
        List<History> deduplicatedList = historyList.stream()
                .collect(Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(History::getSearchContent))),
                        ArrayList::new));
        return ResponseResult.OkResult(deduplicatedList);
    }

    @Override
    public ResponseResult clearHistory(HttpServletRequest request) {
        ResponseResult result = getUserInfo(request);
        if(result.getCode()!=200){
            return result;
        }
        User user = JSON.parseObject(JSON.toJSONString(result.getData()), User.class);
        if(user==null){
            return ResponseResult.ErrorResult(AppHttpCode.SERVICE_ERROR);
        }
        QueryWrapper<History> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",user.getUserId());
        int delete = historyMapper.delete(queryWrapper);
        if(delete>0){
            return ResponseResult.OkResult();
        }
        return ResponseResult.ErrorResult(AppHttpCode.SERVICE_ERROR);
    }

    @Override
    public ResponseResult getSearchContent(String key, String city) {
        if(key == null || city == null){
            return ResponseResult.ErrorResult(AppHttpCode.DATA_NULL);
        }
        ResponseResult postsSearch = postsService.search(new PostsSearchDto(key, city));
        ResponseResult companySearch = companyService.searchQuery(new PostsSearchDto(key, city));
        if(postsSearch.getCode() != 200){
            return postsSearch;
        }
        if(companySearch.getCode() != 200){
            return companySearch;
        }
        Map<String, Object> data = new HashMap<>();
        data.put("posts",postsSearch.getData());
        data.put("company",companySearch.getData());
        return ResponseResult.OkResult(data);
    }

    public ResponseResult getUserInfo(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        // token为”“或者null则未登录
        if(StringUtils.isNullOrEmpty(token)){
            return ResponseResult.ErrorResult(AppHttpCode.LOGIN_AUTH);
        }
        User user = JwtTokenUtils.checkToken(token);
        // 其中有数据缺失则表示token被修改
        if(user.getUserId()==null || (user.getUsername()==null && user.getPhone()==null)){
            return ResponseResult.ErrorResult(AppHttpCode.TOKEN_ERROR);
        }
        return ResponseResult.OkResult(user);
    }
}
